package com.yunwaikeji.gy_tool_library.utils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;

public class GYUriUtils {
    /**
     * Uri转路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String toPath(Context context, Uri uri) {
        String path = null;
        if (uri != null) {
            // content://开头的uri
            if (uri.getScheme().compareTo("content") == 0) {
                Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    try {
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        path = cursor.getString(column_index); // 取出文件路径
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } finally {
                        cursor.close();
                    }
                }
            } else if (uri.getScheme().compareTo("file") == 0) {// file:///开头的uri
                path = uri.getPath();
            }
        }
        return path;
    }

    /**
     * Uri转文件
     *
     * @param context
     * @param uri
     * @return
     */
    public static File toFile(Context context, Uri uri) {
        return new File(toPath(context, uri));
    }
}
